<template>
  <div class="search-menu-layout">
    <el-input prefix-icon="Search" :placeholder="$t('header.message4')" @click="openSearch" />
    <el-dialog v-model="dialogVisible" :title="$t('header.searchTitle')" width="700" :before-close="handleClose">
      <div class="search-layout">
        <el-input
          v-model="searchMenu"
          ref="searchInput"
          :clearable="true"
          prefix-icon="Search"
          class="search-input"
          :placeholder="$t('header.message4')"
          @input="searchHandler"
        />
        <div class="search-result">
          <h3>{{ searchMenu.trim() === "" ? $t("header.history") : $t("header.result") }}</h3>
          <div class="search-list">
            <template v-if="searchHistory.length > 0">
              <div
                v-for="(item, index) in searchHistory"
                :key="item.path"
                :class="{ 'search-item': true, active: index === selectIndex }"
                @click="goMenuItem(item)"
              >
                <el-icon size="16"><Clock /></el-icon>
                <div class="text">{{ item.meta?.title }}</div>
                <el-icon class="close-icon" size="16" @click.stop="closeHostory(item)"><Close /></el-icon>
              </div>
            </template>
            <template v-else>
              <div style="display: flex; align-items: center; justify-content: center">暂无数据</div>
            </template>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ul class="btn-list">
            <li class="btn-item">
              <Icon icon="huiche" />
              <span>{{ $t("header.select") }}</span>
            </li>
            <li class="btn-item">
              <el-icon><Bottom /></el-icon>
              <el-icon><Top /></el-icon>
              <span>{{ $t("header.swatch") }}</span>
            </li>
            <li class="btn-item">
              <span>ESC</span>
              <span>{{ $t("header.close") }}</span>
            </li>
          </ul>
          <el-button type="primary" size="small" :disabled="searchHistory.length <= 0" @click="clearAll" plain>
            {{ $t("header.closeAll") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { InputInstance } from "element-plus";
import { onMounted, onUnmounted, ref, watch } from "vue";
import { debounce } from "@/utils";
import { useAuthStore } from "@/stores";
import type { Menu } from "@/typings";
import { useRouter } from "vue-router";
import { useHistoryStore } from "@/stores/modules/history";

const searchMenu = ref<string>("");
const menuList = ref<Menu[]>([]);
const selectIndex = ref<number>(0);
const useAuth = useAuthStore();
const useHistory = useHistoryStore();
const router = useRouter();
const searchInput = ref<InputInstance | undefined>();
const searchHistory = ref<Menu[]>([]);
const dialogVisible = ref<boolean>(false);

onMounted(() => {
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      dialogVisible.value = false;
      searchMenu.value = "";
      const menuItem = searchHistory.value[selectIndex.value];
      if (!menuItem) return;
      useHistory.addHistory(menuItem);
      router.push(menuItem.path);
    }
    if (e.code === "ArrowUp") {
      selectIndex.value--;
      if (selectIndex.value < 0) {
        selectIndex.value = searchHistory.value.length - 1;
      }
    }
    if (e.code === "ArrowDown") {
      selectIndex.value++;
      if (selectIndex.value > searchHistory.value.length - 1) {
        selectIndex.value = 0;
      }
    }
  };
});

const stopWatch = watch(
  () => useHistory.history,
  (newHistory) => {
    searchHistory.value = newHistory;
  },
  {
    deep: true,
    immediate: true
  }
);

const openSearch = () => {
  selectIndex.value = 0;
  menuList.value = useAuth.flatMenuListGet().filter((item) => item.menuRank === 4);
  searchHistory.value = useHistory.history;
  dialogVisible.value = true;
  setTimeout(() => {
    searchInput.value && searchInput.value.focus();
  });
};

const searchHandler = debounce(() => {
  if (searchMenu.value.trim() === "") {
    searchHistory.value = useHistory.history;
    return;
  }
  searchHistory.value = menuList.value.filter((item: Menu) => item.meta?.title.includes(searchMenu.value));
}, 200);

const goMenuItem = (item: Menu) => {
  dialogVisible.value = false;
  useHistory.addHistory(item);
  searchMenu.value = "";
  router.push(item.path);
};

const closeHostory = (item: Menu) => {
  searchMenu.value = "";
  searchHistory.value = searchHistory.value.filter((item) => item.path !== item.path);
  useHistory.clearOneHistory(item);
};

const handleClose = (done: () => void) => {
  searchMenu.value = "";
  selectIndex.value = 0;
  done();
};

const clearAll = () => {
  searchHistory.value = [];
  searchMenu.value = "";
  selectIndex.value = 0;
  useHistory.clearHistory();
};

onUnmounted(() => {
  stopWatch && stopWatch();
});
</script>

<style scoped lang="scss">
.search-menu-layout {
  width: 230px;
  :deep(.el-dialog__body) {
    background-color: var(--el-search-dialog-bg);
    .search-layout {
      .search-input {
        height: 46px;
      }
      .search-result {
        margin-top: 10px;
        padding: 10px 5px;
        h3 {
          height: 30px;
          font-size: 16px;
        }
        .search-list {
          overflow-y: auto;
          max-height: 300px;
          .search-item {
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin: 6px 0px;
            border-radius: 4px;
            color: var(--el-text-color-primary);
            background-color: var(--el-search-item-bg);
            padding: 0px 20px;
            vertical-align: middle;
            cursor: pointer;
            .text {
              font-size: 14px;
              margin-left: 10px;
              flex: 1;
            }
            .close-icon {
              transition: all 0.2s;
              border-radius: 50%;
            }
            .close-icon:hover {
              transform: rotate(90deg);
              background-color: rgba(0, 0, 0, 0.2);
            }
          }
          .active {
            color: #fff;
            background-color: $primary-color;
          }
        }
      }
    }
  }
  .dialog-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .btn-list {
      display: flex;
      cursor: default;
      .btn-item {
        display: flex;
        align-items: center;
        text-decoration: none;
        padding: 0px 10px;
        span {
          font-size: 14px;
          margin-left: 3px;
        }
      }
    }
  }
}
</style>
